package com.andy.mall.product.service.impl;

import com.andy.mall.product.dao.CategoryBrandRelationDao;
import com.andy.mall.product.vo.Category2Vo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.andy.common.utils.PageUtils;
import com.andy.common.utils.Query;

import com.andy.mall.product.dao.CategoryDao;
import com.andy.mall.product.entity.CategoryEntity;
import com.andy.mall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查找所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        //2、查找所有1级分类,并找出它的子菜单
        List<CategoryEntity> collect = categoryEntities.stream()
                .filter(categoryEntity -> categoryEntity.getCatLevel() == 1)
                .map(menu -> {
                    menu.setChildren(getChildens(menu, categoryEntities));
                    return menu;
                })
                .sorted(Comparator.comparingInt(item -> (item.getSort() == null ? 0 : item.getSort())))
                .collect(Collectors.toList());
        return collect;
    }

    @Override
    public void removeByMeunIds(List<Long> asList) {
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] getCatelogPath(Long catelogId) {
        List<Long> catelogIds= new ArrayList<Long>();
        List<Long> catelogPath=findCatelogIds(catelogId,catelogIds);
        Collections.reverse(catelogPath);  //集合倒序
        return catelogPath.toArray(new Long[catelogPath.size()]);
    }

    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        if(StringUtils.isNotEmpty(category.getName())){
            categoryBrandRelationDao.updateByCatId(category.getCatId(),category.getName());
        }
    }

    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", "0"));
        return categoryEntities;
    }

    @Override
    public Map<String, List<Category2Vo>> getCategory2Json() {
        //1、查询所以1级分类

        List<CategoryEntity> level1Categorys = getLevel1Categorys();

        Map<String, List<Category2Vo>> catalogJson = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //2、查询所以2级分类并组装数据
            List<CategoryEntity> l2List = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));

            List<Category2Vo> category2VoList = new ArrayList<>();

            if (l2List != null) {
                category2VoList = l2List.stream().map(l2 -> {
                    Category2Vo category2Vo = new Category2Vo(l2.getParentCid().toString(), l2.getCatId().toString(), l2.getName(), null);
                    List<CategoryEntity> l3List = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                    if (l3List != null) {
                        List<Category2Vo.Category3Vo> collect = l3List.stream().map(l3 -> {
                            Category2Vo.Category3Vo category3Vo = new Category2Vo.Category3Vo(l3.getCatId().toString(), l3.getName(), l3.getParentCid().toString());
                            return category3Vo;
                        }).collect(Collectors.toList());

                        category2Vo.setCatalog3List(collect);
                    }

                    return category2Vo;
                }).collect(Collectors.toList());
            }


            return category2VoList;
        }));


        return catalogJson;
    }

    private List<Long> findCatelogIds(Long catelogId,List<Long> catelogIds){
        CategoryEntity categoryEntity = baseMapper.selectById(catelogId);
        catelogIds.add(catelogId);
        if(categoryEntity.getParentCid() !=0){
            CategoryEntity category = baseMapper.selectById(categoryEntity.getParentCid());
            findCatelogIds(category.getCatId(),catelogIds);
        }
        return catelogIds;
    }

    /**
     * 使用递归查找所有菜单的子菜单
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> childList = all.stream()
                .filter(item -> item.getParentCid().equals(root.getCatId()))
                .map(menu -> {
                    menu.setChildren(getChildens(menu, all));
                    return menu;
                })
                .sorted(Comparator.comparingInt(item -> (item.getSort() == null ? 0 : item.getSort())))
                .collect(Collectors.toList());
        return childList;
    }

}